package io.bsly.modules.platform.api.douDianApi;

import com.doudian.open.api.order_searchList.OrderSearchListRequest;
import com.doudian.open.api.order_searchList.OrderSearchListResponse;
import com.doudian.open.api.order_searchList.param.OrderSearchListParam;
import com.doudian.open.core.AccessToken;
import com.doudian.open.core.AccessTokenBuilder;
import com.doudian.open.core.GlobalConfig;
import io.bsly.common.utils.Constant;
import io.bsly.common.utils.DateUtils;
import io.bsly.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@Order(20)
public class DouDianApi implements ApplicationRunner {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    DouDianConfigVo douDianConfigVo;

    @Override
    public void run(ApplicationArguments args)  {
        GlobalConfig.initAppKey(douDianConfigVo.getAppKey());
        GlobalConfig.initAppSecret(douDianConfigVo.getAppSecret());
    }

    public AccessToken accessToken(){
        if (redisTemplate.hasKey(Constant.DOUDIAN_ACCESS_TOKEN)){
            AccessToken accessToken = (AccessToken)redisTemplate.opsForValue().get(Constant.DOUDIAN_ACCESS_TOKEN_BEAN);
            return accessToken;
        }
        //指定店铺id
        AccessToken accessToken = AccessTokenBuilder.build(Long.parseLong(douDianConfigVo.getShopId()));
        redisTemplate.opsForValue().set(Constant.DOUDIAN_ACCESS_TOKEN_BEAN,accessToken,accessToken.getExpireIn()-120, TimeUnit.SECONDS);
        return accessToken;
    }

    public void refreshToken(){
        AccessToken refresh = AccessTokenBuilder.refresh(accessToken());
        redisTemplate.opsForValue().set(Constant.DOUDIAN_ACCESS_TOKEN_BEAN,refresh,refresh.getExpireIn()-120, TimeUnit.SECONDS);
    }

    /**
     * 订单列表
     */
    public R doudianOrderList(Long page , Long size, String startTime, String endTime ){
        OrderSearchListRequest request = new OrderSearchListRequest();
        OrderSearchListParam param = request.getParam();
        Long start = DateUtils.stringToLong(startTime, DateUtils.DATE_TIME_PATTERN);
        Long end = DateUtils.stringToLong(endTime, DateUtils.DATE_TIME_PATTERN);
        param.setCreateTimeStart(start);
        param.setCreateTimeEnd(end);
        param.setPage(page);
        param.setSize(size);
        OrderSearchListResponse response = request.execute(accessToken());
        return R.ok().put("data",response);
    }


}
